from datamodel import *

class RuleCondition(object):
  """Hierarchy root for rule conditions"""
  def matches(self, instanceList):
    print "RuleCondition#matches should be overridden"
  
class AssetTypeRuleCondition(RuleCondition):
  """Rule condition which checks asset instance for type"""
  # Asset type to be matched
  def __init__(self, atype):
    self.assetType = atype
    
  def matchesInstance(self, ainstance):
    """Return True iff the type of the asset instance matches this condition"""
    if ainstance.assetType == self.assetType:
      return True
    return False
  
  def matches(self, instanceList):
    for ins in instanceList:
      if self.matchesInstance(ins):
        return True
    return False
  
class AndRuleCondition(RuleCondition):
  """Conjunction of rule conditions"""
  def __init__(self):
    self.children = []
    
  def addChild(self, child):
    self.children.append(child)
    
  def matches(self, instanceList):
    if len(self.children) == 0:
      return True
    for child in self.children:
      if not child.matches(instanceList):
        return False
    return True
  
  

class Rule(object):  
  """Rule that can fire"""
  # Condition for this rule, document type to be added
  def __init__(self, cond, docType):
    self.condition = cond
    self.documentType = docType
    
  def apply(self, user, instanceList):
    if self.condition.matches(instanceList):
      # Create an instance of document place
      # Make a better name and save the causing instances
      longName = self.documentType + " on " + str(instanceList)
      place = DocumentPlace(user=user, documentType=self.documentType, name=longName)
      place.put()
  
class RuleBase(object):
  def __init__(self):
    self.rules = []
    rule = Rule(AssetTypeRuleCondition("Self"), "Health insurance")
    self.rules.append(rule)
    
  def apply(self, user, instanceList):
    for rule in self.rules:
      rule.apply(user, instanceList)
        